package com.guet.main.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class MailClient {
    //日志
    private static final Logger logger= LoggerFactory.getLogger(MailClient.class);
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private RedisUtil redisUtil;
    @Value("${spring.mail.username}")
    private String from;

    private String code;
    private String content;
    public boolean sendMail(String to){
        try{
            code = GetVerCode.generateVerCode();
            content = "尊敬的用户,您好:\n"
                    + "\n本次请求的邮件验证码为:" + code + ",本验证码5分钟内有效，请及时输入。（请勿泄露此验证码）\n"
                    + "\n如非本人操作，请忽略该邮件。\n(这是一封自动发送的邮件，请不要直接回复）";
            MimeMessage message=mailSender.createMimeMessage();
            MimeMessageHelper helper=new MimeMessageHelper(message);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject("会议室预约系统|验证码");
            helper.setText(content,true);
            mailSender.send(helper.getMimeMessage());
            redisUtil.set(to,code,300);
            return true;
        }catch(MessagingException e){
            logger.error("发送邮件失败"+e.getMessage());
            return false;
        }
    }
}

